#!/bin/bash

REPOS_URL="https://gitee.com/wx-rdc/secloud-quickstart"

BASE_PATH="$HOME/.docker"

NETWORK_NAME="secloud-network"
MYSQL_DATA="ca-db-data"
MYSQL_NAME="ca-mysql"

# registry path
REGISTRY="svr01:5000"

CA_NAME="chainmaker-ca"
CA_VERSION="2.2.0"

create_volume() {
  docker volume create $MYSQL_DATA
}

start_mysql() {
  docker run -p 13306:3306 -d \
        -e MYSQL_ROOT_PASSWORD=123456 \
        -e MYSQL_DATABASE=chainmaker_ca \
        -v $BASE_PATH/conf/my.cnf:/etc/mysql/my.cnf \
        -v $MYSQL_DATA:/var/lib/mysql \
        --restart=on-failure:5 \
        --name $MYSQL_NAME \
        --network $NETWORK_NAME \
        mysql:8.0
  echo "waiting for database initialization..."      
  sleep 15
  docker logs --tail=10 $MYSQL_NAME
}

start_ca() {
  wget -O "$BASE_PATH/ca.tar.gz" $REPOS_URL/raw/master/ca.tar.gz
  tar xzf $BASE_PATH/ca.tar.gz -C $BASE_PATH
  rm -f $BASE_PATH/ca.tar.gz
  mkdir -p $BASE_PATH/ca/log
  docker run -d \
    -p 8096:8090 \
    -w /chainmaker-ca \
    -v $BASE_PATH/ca/conf:/chainmaker-ca/conf \
    -v $BASE_PATH/ca/log:/log \
    -v $BASE_PATH/ca/crypto-config:/crypto-config \
    -v $BASE_PATH/ca/sansec-pkcs11/pkcs11:/usr/local/lib64/pkcs11 \
    -v $BASE_PATH/ca/sansec-pkcs11/etc:/etc \
    --name $CA_NAME \
    --network $NETWORK_NAME \
    --restart always \
    $REGISTRY/$CA_NAME:$CA_VERSION \
    bash -c "./chainmaker-ca -config ./conf/config.yaml"
  sleep 2s
  docker logs $CA_NAME
  echo "chainmaker-ca server start!"
}

if [ ! -d $BASE_PATH ]; then
  mkdir -p $BASE_PATH
fi

if [ -z $(docker volume ls -q --filter name=$MYSQL_DATA) ] ; then
  echo "create volume"
  create_volume
else
  echo "volume $MYSQL_DATA already existed"
fi

if [ -z $(docker ps -q --filter name=$MYSQL_NAME) ] ; then
  echo "start mysql"
  start_mysql
else
  echo "mysql already running"
fi

if [ -z $(docker ps -q --filter name=$CA_NAME) ] ; then
  echo "start chainmaker-ca server"
  start_ca
else
  echo "chainmaker-ca server already running"
fi
